<template>
  <UserLayout :active-index="activeIndex" :active-menu="activeMenu">
    <div class="maintenance-management-content">
      <!-- 页面标题 -->
      <div class="page-header">
        <h2>维修申请管理</h2>
        <div class="header-stats">
          <el-tag type="warning">待处理: {{ pendingCount }}</el-tag>
          <el-tag type="success">已处理: {{ processedCount }}</el-tag>
        </div>
      </div>

      <!-- 筛选器 -->
      <div class="filter-section">
        <el-row :gutter="20">
          <el-col :span="6">
            <el-select v-model="filterStatus" placeholder="筛选状态" @change="fetchMaintenanceList">
              <el-option label="全部" value="" />
              <el-option label="待处理" :value="0" />
              <el-option label="已处理" :value="1" />
              <el-option label="已拒绝" :value="2" />
            </el-select>
          </el-col>
          <el-col :span="6">
            <el-button @click="fetchMaintenanceList" icon="Refresh">刷新</el-button>
          </el-col>
        </el-row>
      </div>

      <!-- 维修申请列表 -->
      <div class="maintenance-list">
        <el-card v-for="item in maintenanceList" :key="item.maintenanceId" class="maintenance-item">
          <div class="maintenance-header">
            <div class="house-info">
              <h3>{{ item.house?.houseSummary || '房源信息' }}</h3>
              <p>{{ item.house?.houseLocation || '位置信息' }}</p>
              <p><strong>租客：</strong>{{ item.user?.username || '租客信息' }}</p>
            </div>
            <div class="status-badge">
              <el-tag :type="getStatusType(item.maintenanceStatus)">
                {{ getStatusText(item.maintenanceStatus) }}
              </el-tag>
            </div>
          </div>
          
          <div class="maintenance-content-detail">
            <p><strong>故障描述：</strong>{{ item.faultDescription }}</p>
            <p><strong>申请时间：</strong>{{ formatDate(item.createTime) }}</p>
            <div v-if="item.faultPhoto" class="fault-photos">
              <strong>故障照片：</strong>
              <div class="photo-list">
                <img 
                  v-for="(photo, index) in item.faultPhoto.split(',')" 
                  :key="index"
                  :src="photo" 
                  class="fault-photo"
                  @click="previewImage(photo)"
                />
              </div>
            </div>
          </div>
          
          <div class="maintenance-actions" v-if="item.maintenanceStatus === 0">
            <el-button type="success" size="small" @click="handleMaintenance(item, 1)">
              标记已处理
            </el-button>
            <el-button type="danger" size="small" @click="handleMaintenance(item, 2)">
              拒绝处理
            </el-button>
          </div>
        </el-card>
        
        <el-empty v-if="maintenanceList.length === 0" description="暂无维修申请" />
      </div>

      <!-- 处理对话框 -->
      <el-dialog v-model="showHandleDialog" title="处理维修申请" width="500px">
        <el-form :model="handleForm" label-width="100px">
          <el-form-item label="处理结果">
            <el-tag :type="handleForm.status === 1 ? 'success' : 'danger'">
              {{ handleForm.status === 1 ? '标记已处理' : '拒绝处理' }}
            </el-tag>
          </el-form-item>
          
          <el-form-item label="备注说明">
            <el-input
              v-model="handleForm.remark"
              type="textarea"
              :rows="4"
              :placeholder="handleForm.status === 1 ? '请输入处理说明' : '请输入拒绝原因'"
            />
          </el-form-item>
        </el-form>
        
        <template #footer>
          <el-button @click="showHandleDialog = false">取消</el-button>
          <el-button type="primary" @click="confirmHandle" :loading="handling">确认</el-button>
        </template>
      </el-dialog>
    </div>
  </UserLayout>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Refresh } from '@element-plus/icons-vue'
import UserLayout from '@/components/layout/UserLayout.vue'
import api from '@/utils/api'
import { getToken, canAccessLandlordFeatures, getUserInfo } from '@/utils/auth'
import { useRouter } from 'vue-router'

const router = useRouter()
const activeIndex = ref('4')
const activeMenu = ref('landlord')

// 维修申请列表
const maintenanceList = ref([])
const loading = ref(false)
const filterStatus = ref('')

// 处理对话框
const showHandleDialog = ref(false)
const handling = ref(false)
const currentItem = ref(null)

// 处理表单
const handleForm = ref({
  status: 1,
  remark: ''
})

// 统计数据
const pendingCount = computed(() => {
  return maintenanceList.value.filter(item => item.maintenanceStatus === 0).length
})

const processedCount = computed(() => {
  return maintenanceList.value.filter(item => item.maintenanceStatus === 1).length
})

// 获取维修申请列表
const fetchMaintenanceList = async () => {
  loading.value = true
  try {
    const response = await api.get('/maintenance/landlord/list', {
      headers: { info: getToken() }
    })
    if (response.data.code === 200) {
      let list = response.data.data || []
      
      // 根据状态筛选
      if (filterStatus.value !== '') {
        list = list.filter(item => item.maintenanceStatus === filterStatus.value)
      }
      
      maintenanceList.value = list
    } else {
      ElMessage.error(response.data.message || '获取维修申请列表失败')
    }
  } catch (error) {
    ElMessage.error('获取维修申请列表失败')
  } finally {
    loading.value = false
  }
}

// 处理维修申请
const handleMaintenance = (item, status) => {
  currentItem.value = item
  handleForm.value = {
    status: status,
    remark: ''
  }
  showHandleDialog.value = true
}

// 确认处理
const confirmHandle = async () => {
  if (!currentItem.value) return
  
  handling.value = true
  try {
    const response = await api.put(
      `/maintenance/landlord/handle/${currentItem.value.maintenanceId}`,
      null,
      {
        headers: { info: getToken() },
        params: {
          status: handleForm.value.status,
          remark: handleForm.value.remark
        }
      }
    )
    
    if (response.data.code === 200) {
      ElMessage.success('处理成功')
      showHandleDialog.value = false
      fetchMaintenanceList()
    } else {
      ElMessage.error(response.data.message || '处理失败')
    }
  } catch (error) {
    ElMessage.error('处理失败，请重试')
  } finally {
    handling.value = false
  }
}

// 获取状态类型
const getStatusType = (status) => {
  const statusMap = {
    0: 'warning',  // 待处理
    1: 'success',  // 已处理
    2: 'danger'    // 已拒绝
  }
  return statusMap[status] || 'info'
}

// 获取状态文本
const getStatusText = (status) => {
  const statusMap = {
    0: '待处理',
    1: '已处理',
    2: '已拒绝'
  }
  return statusMap[status] || '未知状态'
}

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return ''
  return new Date(dateString).toLocaleString('zh-CN')
}

// 预览图片
const previewImage = (imageUrl) => {
  // 这里可以实现图片预览功能
  window.open(imageUrl, '_blank')
}

// 页面加载时检查权限并获取数据
onMounted(() => {
  if (!canAccessLandlordFeatures()) {
    const userInfo = getUserInfo()
    if (userInfo?.role === 1) {
      ElMessage.error('您还不是房东，请先发布房源成为房东')
    } else {
      ElMessage.error('用户角色不符合访问条件')
    }
    router.push('/')
    return
  }
  
  fetchMaintenanceList()
})
</script>

<style scoped>
.maintenance-management-content {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding: 20px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 12px;
  color: white;
  box-shadow: 0 4px 15px rgba(102, 126, 234, 0.4);
}

.page-header h2 {
  color: white;
  margin: 0;
  font-size: 24px;
  font-weight: 600;
}

.header-stats {
  display: flex;
  gap: 10px;
}

.filter-section {
  margin-bottom: 20px;
  padding: 15px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.maintenance-list {
  display: grid;
  gap: 20px;
}

.maintenance-item {
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
}

.maintenance-item:hover {
  transform: translateY(-2px);
  box-shadow: 0 8px 25px rgba(0, 0, 0, 0.15);
}

.maintenance-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 15px;
}

.house-info h3 {
  margin: 0 0 5px 0;
  color: #2c3e50;
  font-size: 18px;
}

.house-info p {
  margin: 5px 0;
  color: #7f8c8d;
  font-size: 14px;
}

.maintenance-content-detail {
  margin-bottom: 15px;
}

.maintenance-content-detail p {
  margin: 8px 0;
  color: #34495e;
}

.fault-photos {
  margin-top: 10px;
}

.photo-list {
  display: flex;
  gap: 10px;
  margin-top: 5px;
}

.fault-photo {
  width: 80px;
  height: 80px;
  object-fit: cover;
  border-radius: 8px;
  cursor: pointer;
  border: 2px solid #e0e0e0;
  transition: all 0.3s ease;
}

.fault-photo:hover {
  border-color: #667eea;
  transform: scale(1.05);
}

.maintenance-actions {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style>
